function [negloglik] = log_det_B(hyps, cov_func, n, n_class, X, y, approxF)
% a function evaluating  1/2 log det (B)
% where B = I + sqrt(W)Ksqrt(W)
% by Mark Norrish, 2011
% note: actually uses a bunch of other equations, esp. for derivations
% Modified by ebonilla 09/11/2012

[f, F , bigK, W] = ...
    get_approx_laplace(hyps, cov_func, n, n_class, X, y, approxF);

B = bigK*W + eye(n*n_class); % B =  KW + I; or not quite but whatever

fKf = 0;
for i = 1:n_class
  rn = 1+(i-1)*n:i*n;
  fKf = fKf + f(rn)' / bigK(rn, rn) * f(rn);
end
ldb = log(det(B));
if isinf(ldb + fKf) | isnan(ldb + fKf)
  disp('loglik is screwballing');
  ldb
  fKf
end
negloglik = 0.5 * fKf - f' * y + sum(log(sum(exp(F')))) + 0.5 * ldb;

%0.5*log(det(B));
%
% We cannot use the Cholesky decomposition here as B is not symmetric
% XY is symmetric if and only if X and Y commute, i.e. XY = YX 
% otherwise we could do:
% from log(det(B)) for some Bs
% log(Det(B)) = 2*sum(log (L_ii)) --> sum(log (L_ii)) = 0.5*log(Det(B))
% 
%L = chol(B, 'lower');
%negloglik2 = sum(log(diag(L)));
%fprintf('nl1 - nl2=%.6f\n', negloglik-negloglik2);
%
% Alternatively, we could use:
% B = (KW + I) = K(W+K^{-1})
% logdet(B) = logdet(K) + logdet(W+K^{-1})

return;







